package com.test.list2tree;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.test.utils.FileUtil;
import com.test.utils.JsonUtil;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.*;

public class List2TreeDemo {
    public static void main(String[] args) throws Exception {
        String jsonFilePath = "D:\\works\\self\\self_data\\desktop\\精友数据模型\\车辆结构.json";
        String s = FileUtils.readFileToString(new File(jsonFilePath), "UTF-8");
        Result<ResultData> result = JsonUtil.json2ObjUseRef(s, new TypeReference<Result<ResultData>>() {});
        List<Structure> list = result.getResult().getPartGroupList();

        List<Structure> zeroList = new ArrayList<>();
        Map<String, List<Structure>> tmpMap = new LinkedHashMap<>();
        for (Structure st : list) {
            if (Objects.equals(st.getPid(), "0")) {
                zeroList.add(st);
            } else {
                String level = st.getLevel();
                String pId = st.getPid();
                if (tmpMap.containsKey(level + "-" + pId)) {
                    List<Structure> tmpList = tmpMap.get(level + "-" + pId);
                    tmpList.add(st);
                } else {
                    List<Structure> tmpList = new ArrayList<>();
                    tmpList.add(st);
                    tmpMap.put(level + "-" + pId, tmpList);
                }
            }
        }
        for (Structure st : zeroList) {
            generateTree(st, tmpMap);
        }
        System.out.println(JsonUtil.toJson(zeroList));
    }

    private static Structure generateTree(Structure st, Map<String, List<Structure>> tmpMap) {
        int level = Integer.parseInt(st.getLevel()) + 1;
        List<Structure> tmpList = tmpMap.get(level + "-" + st.getId());
        if (tmpList != null && tmpList.size() > 0) {
            st.setChildren(tmpList);
            for (Structure structure : tmpList) {
                generateTree(structure, tmpMap);
            }
        }
        return st;
    }
}
